from flask import render_template_string, request

from pathlib import Path

from config import GlobalContextData

# flask error handler
error_dir = Path.cwd() / 'static' / 'error'
html_404 = error_dir / '404.html'
html_500 = error_dir / '500.html'
html_404_debug = error_dir / '404_debug.html'
html_500_debug = error_dir / '500_debug.html'

def handle_404_error(e):
    if GlobalContextData.Debug:
        import traceback
        trace = traceback.format_exc()
        return render_template_string(html_404_debug.read_text(encoding='utf-8'), request=request, error=e, traceback=trace), 404
    else:
        return render_template_string(html_404.read_text(encoding='utf-8'), error=e), 404

def handle_500_error(e):
    if GlobalContextData.Debug:
        import traceback
        trace = traceback.format_exc()
        return render_template_string(html_500_debug.read_text(encoding='utf-8'), request=request, error=e, traceback=trace)
    else:
        return render_template_string(html_500.read_text(encoding='utf-8'), error=e), 500